//
//  KKWritingBoard.m
//  WritingBoard
//
//  Created by Mac mini on 16/1/22.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKWritingBoardView.h"

@interface KKLineItem : NSObject

@property (nonatomic, assign) CGPoint kk_beginPoint;
@property (nonatomic, assign) CGPoint kk_endPoint;

@end

@implementation KKLineItem

+ (instancetype)lineItemWithBeginPoint:(CGPoint)beginPoint endPoint:(CGPoint)endPoint {
    
    KKLineItem *lineItem = [KKLineItem new];
    lineItem.kk_beginPoint = beginPoint;
    lineItem.kk_endPoint = endPoint;
    return lineItem;
}

@end


#pragma mark - KKWritingBoard methods

@interface KKWritingBoardView() {
    
    NSMutableArray *_kk_lineItems;
    
    KKLineItem *_kk_currentLineItem;
}

@end

@implementation KKWritingBoardView

#pragma mark - Public methods

- (void)reset {
    
    [_kk_lineItems removeAllObjects];
    [self setNeedsDisplay];
}

#pragma mark - Private methods

- (BOOL) isMultipleTouchEnabled {
    return NO;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    if (_kk_lineItems == nil) {
        _kk_lineItems = [NSMutableArray array];
    }
    
    [self.undoManager beginUndoGrouping];
    
    for (UITouch *touch in touches) {
        
        CGPoint point = [touch locationInView: self];
        
        KKLineItem *lineItem = [KKLineItem lineItemWithBeginPoint: point endPoint: point];
        [_kk_lineItems addObject: lineItem];
        
        _kk_currentLineItem = lineItem;
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    for (UITouch *touch in touches) {
        
        CGPoint point = [touch locationInView: self];
        [_kk_currentLineItem setKk_endPoint: point];
        
        if (_kk_currentLineItem) {
            [_kk_lineItems addObject: _kk_currentLineItem];
        }
        
        KKLineItem *lineItem = [KKLineItem lineItemWithBeginPoint: point endPoint: point];
        [_kk_lineItems addObject: lineItem];
        _kk_currentLineItem = lineItem;
    }
    
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self setNeedsDisplay];
    [self.undoManager endUndoGrouping];
}

- (void)drawRect:(CGRect)rect {
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, 3.0);
    
    for (KKLineItem *lineItem in _kk_lineItems) {
        
        CGContextMoveToPoint(context, [lineItem kk_beginPoint].x, [lineItem kk_beginPoint].y);
        CGContextAddLineToPoint(context, [lineItem kk_endPoint].x, [lineItem kk_endPoint].y);

    }
    CGContextStrokePath(context);
}

@end
